import XLSX from "xlsx-js-style";
import FileSaver from "file-saver";

const columns = [
    "HK",
    "HZ",
    "HZB",
    "H-K-2-黄",
    "H1-K-2-黄",
    "H-K-4",
    "H1-K-4",
    "H2-K-4",
    "H1-Z-2",
    "H2-Z-2",
    "H-K-2",
    "H1-K-2",
    "H2-K-2",
    "HKT",
    "H1-Z-3",
    "H2-Z-3",
    "HZT-2",
    "HZT",
    "LPKK",
    "H-K-3",
    "H1-K-3",
    "H2-K-3",
    "H1-Z-1",
    "H2-Z-1",
    "H-K-1",
    "H1-K-1",
    "H2-K-1",
    "H1-Z-4",
    "H2-Z-4",
    "H-KF-1",
    "H1-KF-2",
    "H2-KF-3",
    "HG",
    "HGD",
    "H-K-5",
    "H1-K-5",
    "H2-K-5",
    "TS-1",
    "H-K-6",
    "H1-K-6",
    "H2-K-6",
    "LJT",
    "DZ",
    "NNDZ",
    "DP-4",
    "DP-3",
    "DP-2",
    "DP-1",
    "S-Z-单",
    "S-Z-双",
    "SZB-左",
    "SZB-右",
    "SZB-中",
    "S-K-左",
    "S-K-右",
    "S-K-中",
    "S-K-13",
    "S2-K-10",
    "S-K-1",
    "S-K-2",
    "S-K-3",
    "S-K-4",
    "S-K-5",
    "S-Z-2",
    "S-K-6",
    "S2-K-1",
    "S2-K-2",
    "S2-K-3",
    "S2-K-4",
    "S2-Z-1",
    "S2-K-5",
    "S2-K-6",
    "S-K-9",
    "S2-K-9",
    "S-K-10",
    "SZ-4",
    "S-K-12",
    "ZJ",
    "SZ-3",
    "S-K-11",
    "S-K-12",
    "S-K-8",
    "S2-K-8",
    "DK-1",
    "DK-2",
    "XK-1",
    "XK-2",
    "HZ-DP",
    "S-K-14",
    "S2-K-13",
    "M8-50",
    "M8",
    "M8-20",
    "M4-16",
    "TS-2",
    "GL",
    "S-DT-1",
    "S2-DT-2",
    "DT-1",
    "DT-2",
    "DT-3",
    "DT-4",
    "DT-5",
    "DT-6",
    "SYD",
    "ZYTC",
    "XXTC",
    "SCTC",
    "PBTC",
    "CKDB",
    "QCJ-1",
    "QCJ-1.5",
    "QCJ-2",
    "QCJ-4",
    "QCJ-6",
    "QCJ-3",
    "QCJ-5",
    "QCJ-7",
    "ZCJ-1",
    "ZCJ-2",
    "ZCJ-4",
    "ZCJ-5",
    "ZCJ-3",
];

function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
}

const quinn = {
    expTable(props) {
        let {
            sort = true,
            columns = [],
            datamerges = [],
            fileName = "导出文件",
            type = "file",
            data,
        } = props;
        const headers = [columns.map((e) => e.label)];
        const keys = columns.map((e) => e.prop);
        data = data.map((e, i) => {
            const res = {};
            keys.forEach((k) => {
                try {
                    res[k] = e[k];
                } catch (e) {
                }
            });
            res.s = {
                alignment: {
                    horizontal: "center", //水平居中
                },
            };
            return res;
        });
        // return console.log(data);
        let key = "";
        const ws = XLSX.utils.book_new();
        XLSX.utils.sheet_add_aoa(ws, headers);
        XLSX.utils.sheet_add_json(ws, data, {
            origin: "A" + (headers.length + 1),
            skipHeader: true,
        });
        let wscols = columns.map(() => ({wch: 20}));
        ws["!cols"] = wscols;
        if (datamerges.length) ws["!merges"] = datamerges;
        const wb = {
            Sheets: {
                Sheet1: ws,
            },
            SheetNames: ["Sheet1"],
        };
        var title = fileName;
        const wopts = {
            bookType: "xlsx",
            bookSST: false,
            type: "binary",
        };
        const blob = new Blob([s2ab(XLSX.write(wb, wopts))], {
            type: "application/octet-stream",
        });
        title = title + "." + (wopts.bookType == "biff2" ? "xls" : wopts.bookType);
        if (type == "blob") return new File([blob], title);
        FileSaver.saveAs(blob, title);
    },
    exportExcel(props) {
        let {
            sort = true,
            headers = [
                [
                    "序号",
                    "产品编码",
                    "配件名称",
                    "规格",
                    "单位",
                    "颜色",
                    "总数量",
                    "拣货签名",
                ],
            ],
            datamerges = [],
            defaultTitle = "出库单",
            type = "file",
            productMap = window?.g_config?.productMap || {},
            productSort = window?.g_config?.productSort || [],
            productColumns = window?.g_config?.productColumns || {},
            group = true,
            data,
        } = props;
        if (sort)
            data = data.sort(
                (a, b) =>
                    productSort.indexOf(a.productCode) -
                    productSort.indexOf(b.productCode)
            );
        // const list = ['ZYM-L-148', 'ZYM-Z-114', 'ZYM-Z-115'];
        // data.forEach(item => {
        //     if (list.includes(item.productCode)) {
        //         item.isAddition = 0;
        //     }
        // });
        const withAddition = data.filter(item => item.isAddition == 1);
        const noAddition = data.filter(item => item.isAddition == 0);
        data = noAddition.map((e, i) => {
            const {productCode, productName, norms, unit, count, colour} = e;
            return {
                i: i + 1,
                productCode,
                productName,
                norms,
                unit,
                colour,
                count,
                s: {
                    alignment: {
                        horizontal: "center", //水平居中
                    },
                },
            };
        });
        let key = "";
        let groupNum = 0
        if (group)
            // return console.log(data);
            for (let i = 0; i < data.length; i++) {
                const item = data[i];
                const k = productMap[item.productCode];
                // return console.log(k,);
                if (k != key) {
                    data.splice(i, 0, {
                        i: k,
                        // warehousePosition: k,
                        productCode: k,
                        productName: k,
                        norms: k,
                        unit: k,
                        colour: k,
                        count: k,
                    });
                    groupNum++
                    datamerges.push({
                        s: {r: i + 1, c: 0},
                        e: {r: i + 1, c: headers[0].length - 1},
                    });
                    i++;
                    key = k;
                }
            }
        // return;
        data.push({
            i: (data.length - groupNum) + 1,
            // warehousePosition: el.warehousePosition,
            productCode: '',
            productName: '弧形侧网',
            norms: '',
            unit: '',
            colour: '',
            count: '',
            s: {
                alignment: {
                    horizontal: "center", //水平居中
                },
            },
        })
        data.push({
            i: (data.length - groupNum) + 1,
            // warehousePosition: el.warehousePosition,
            productCode: '',
            productName: '收银台购物袋支架',
            norms: '',
            unit: '',
            colour: '',
            count: '',
            s: {
                alignment: {
                    horizontal: "center", //水平居中
                },
            },
        })
        data[data.length + 1] = [""]
        withAddition.map((el, index) => {
            data.push({
                i: index + 1,
                // warehousePosition: el.warehousePosition,
                productCode: el.productCode,
                productName: el.productName,
                norms: el.norms,
                unit: el.unit,
                colour: el.colour,
                count: el.count,
                s: {
                    alignment: {
                        horizontal: "center", //水平居中
                    },
                },
            });
        })
        const ws = XLSX.utils.book_new();
        //将二维数组中的数据添加到已有的worksheet中
        XLSX.utils.sheet_add_aoa(ws, headers);
        //将js对象中的数据添加到已有的worksheet中。
        XLSX.utils.sheet_add_json(ws, data, {
            origin: "A" + (headers.length + 1),
            skipHeader: true,
        });


        let wscols = [
            {wch: 6},
            {wch: 15},
            {wch: 15},
            {wch: 35},
            {wch: 15},
            {wch: 10},
            {wch: 15},
            {wch: 15},
        ];
        ws["!cols"] = wscols;
        ws["!merges"] = datamerges;

        for (const key in ws) {
            if (
                key.indexOf("!") === -1 &&
                Object.hasOwnProperty.call(ws, key) &&
                Object.hasOwnProperty.call(ws[key], "v")
            ) {
                ws[key].s = {
                    ...(ws[key].s || {}),
                    alignment: {
                        horizontal: "center",
                        vertical: "center",
                        wrap_text: true,
                    },
                    ...(Object.keys(productColumns).includes(ws[key].v)
                        ? {
                            fill: {
                                fgColor: {rgb: "43CD80"},
                            },
                        }
                        : {}),
                };
            }
        }

        const wb = {
            Sheets: {
                Sheet1: ws,
            },
            SheetNames: ["Sheet1"],
        };
        var title = defaultTitle || "列表";
        const wopts = {
            bookType: "xlsx",
            bookSST: false,
            type: "binary",
        };
        // return console.log(ws, wb);
        const blob = new Blob([s2ab(XLSX.write(wb, wopts))], {
            type: "application/octet-stream",
        });
        title = title + "." + (wopts.bookType == "biff2" ? "xls" : wopts.bookType);
        if (type == "blob") return new File([blob], title);
        FileSaver.saveAs(blob, title);
    },
    setStorage(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            localStorage.setItem(key, value);
        }
    },
    getStorage(key) {
        let value = localStorage.getItem(key);
        try {
            value = JSON.parse(value);
        } catch (e) {
        }
        return value;
    },
    removeStorage(key) {
        localStorage.removeItem(key);
    },
    clearStorage() {
        localStorage.clear();
    },
    guid(prefix = "", surfix = "") {
        const tmp = "xxxyxxx-yxxx-";
        let res = tmp.concat(+new Date()).replace(/[xy]/g, (c) => {
            const r = (Math.random() * 16) | 0;
            const v = c === "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
        return `${prefix ? prefix + "-" : ""}${res}${surfix ? "-" + surfix : ""}`;
    },
    $acc: (function () {
        /**
         * floatObj 包含加减乘除四个方法，能确保浮点数运算不丢失精度
         * floatObj.add(0.1, 0.2) >> 0.3
         * floatObj.mul(19.9, 100) >> 1990
         */

        function toFixed(num, s) {
            var times = Math.pow(10, s);
            var des = num * times + 0.5;
            des = parseInt(des, 10) / times;
            return des;
        }

        function isInteger(obj) {
            return Math.floor(obj) === obj;
        }

        function toInteger(floatNum) {
            var ret = {
                times: 1,
                num: 0,
            };
            var isNegative = floatNum < 0;
            if (isInteger(floatNum)) {
                ret.num = floatNum;
                return ret;
            }
            var strfi = floatNum + "";
            var dotPos = strfi.indexOf(".");
            var len = strfi.substr(dotPos + 1).length;
            var times = Math.pow(10, len);
            var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10);
            ret.times = times;
            if (isNegative) {
                intNum = -intNum;
            }
            ret.num = intNum;
            return ret;
        }

        function operation(a, b, digits, op) {
            var o1 = toInteger(a);
            var o2 = toInteger(b);
            var n1 = o1.num;
            var n2 = o2.num;
            var t1 = o1.times;
            var t2 = o2.times;
            var max = t1 > t2 ? t1 : t2;
            var result = null;
            switch (op) {
                case "add":
                    if (t1 === t2) {
                        // 两个小数位数相同
                        result = n1 + n2;
                    } else if (t1 > t2) {
                        // o1 小数位 大于 o2
                        result = n1 + n2 * (t1 / t2);
                    } else {
                        // o1 小数位 小于 o2
                        result = n1 * (t2 / t1) + n2;
                    }
                    return result / max;
                case "sub":
                    if (t1 === t2) {
                        result = n1 - n2;
                    } else if (t1 > t2) {
                        result = n1 - n2 * (t1 / t2);
                    } else {
                        result = n1 * (t2 / t1) - n2;
                    }
                    return result / max;
                case "mul":
                    result = (n1 * n2) / (t1 * t2);
                    return result;
                case "div":
                    result = (n1 / n2) * (t2 / t1);
                    return result;
            }
        }

        function add(a, b, digits) {
            return operation(a, b, digits, "add");
        }

        function sub(a, b, digits) {
            return operation(a, b, digits, "sub");
        }

        function mul(a, b, digits) {
            return operation(a, b, digits, "mul");
        }

        function div(a, b, digits) {
            return operation(a, b, digits, "div");
        }

        return {
            toFixed,
            add,
            sub,
            mul,
            div,
        };
    })(),
};
export default quinn;

